//
//  SecondViewController.m
//  HandWork
//
//  Created by 王阳阳 on 16/1/18.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SecondViewController.h"
#import "ShopTTableViewCell.h"
#import "ShopModel.h"
#import <UIImageView+WebCache.h>
#import "MaterialCollectionViewCell.h"
#import "HeaderView.h"
#import "CarouselPicture.h"
#import "MaterHeaderView.h"
#import "SecondTableviewContentViewController.h"
#import "SecondTwoViewController.h"
#import "SearchViewController.h"
@interface SecondViewController ()<UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
{
    NSInteger _page;
}
@property (nonatomic, retain) UITableView *tableview;//tableview手工市集
@property (nonatomic, retain) UIScrollView *scrollview;//scrollView
@property (nonatomic, retain) UICollectionView *materialView;//collectionView 材料市集
@property (nonatomic, retain) NSMutableArray *dataArr;//手工市集数据数组
@property (nonatomic, retain) NSMutableArray *mDataArr;//材料市集数据数组
@property (nonatomic, retain) UICollectionReusableView *materheader;//collectionView头部
@property (nonatomic, retain)NSMutableArray *btnArr;//手工市集 材料市场 数组按钮
@property (nonatomic, retain)NSMutableArray *lineArr;//红线数组
@end

@implementation SecondViewController

- (void)dealloc
{
    [_tableview release];
    [_scrollview release];
    [_materialView release];
    [_dataArr release];
    [_mDataArr release];
    [_materheader release];
    [_btnArr release];
    [_lineArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
 self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:@selector(s)];
    self.title= @"购买";
    //数据处理
    [self data];
    [self datacol];
    
    //scrollView
    self.scrollview = [[UIScrollView alloc]initWithFrame:self.view.frame];//创建
    [self.view addSubview:self.scrollview];//添加
    self.scrollview.delegate= self;//代理人
    self.scrollview.pagingEnabled = YES;//整页翻动
    self.scrollview.contentSize =  CGSizeMake(self.view.frame.size.width * 2, 0);//实际内容
    [_scrollview release];
    
    
    
    
    #pragma mark - 手工市集
    //内容创建
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableview.delegate = self;//设置代理人
    self.tableview.dataSource = self;//设置代理人
    [self.scrollview addSubview:self.tableview];//吧tableview添加到scrollView上
    [_tableview registerClass:[ShopTTableViewCell class] forCellReuseIdentifier:@"cell"];//重用池
    [_tableview release];
  
    
    #pragma mark - collectionView材料市场
    //layout布局
    UICollectionViewFlowLayout *materialLayout = [[UICollectionViewFlowLayout alloc]init];
    materialLayout.minimumLineSpacing = 10;
    materialLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width / 2 - 30, 200);//item大小
    materialLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);//边距
    materialLayout.scrollDirection = UICollectionViewScrollDirectionVertical;//竖向滑动
    //头部区域
    materialLayout.headerReferenceSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 110);
    //创建ColletionView 材料市场内容
    self.materialView = [[UICollectionView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width, 50, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:materialLayout];//
    self.materialView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    //代理
    self.materialView.delegate = self;
    self.materialView.dataSource = self;
    self.materialView.backgroundColor = [UIColor whiteColor];//背景颜色
    [self.scrollview addSubview:self.materialView];//把collectionview添加scrollView上
//    self.materialView
    [_materialView registerClass:[MaterialCollectionViewCell class] forCellWithReuseIdentifier:@"matercell"];//collectionView重用池
    //头部重用池
    [_materialView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"materheader"];
    [_materialView release];
    [materialLayout release];
    //view上的scrollView
    [self creatScrol];
    //tableview的header
    [self createView];
    [self TableviewRefresh];//TbaleView刷新加载
//    [self CollectionRefresh];
    
}
#pragma mark - 材料市集collectionView从重用池获取头部
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    self.materheader = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"materheader" forIndexPath:indexPath];
   
    return _materheader;
}
#pragma mark - 头部区域
- (void)creat
{
//    头部View
    UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 110)];
    bgview.backgroundColor = [UIColor redColor];
    [self.materheader addSubview:bgview];
    [bgview release];
    //view上的CollectionView 按钮
    MaterHeaderView *h = [[MaterHeaderView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 120)];
    h.backgroundColor = [UIColor yellowColor];
    [bgview addSubview:h];
    [h release];
}
#pragma mark - 导航栏下面的scrollView
- (void)creatScrol
{
    //创建View
    UIView *viewsc =[[UIView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 40)];
    viewsc.backgroundColor = [UIColor whiteColor];//背景颜色
    [self.view addSubview:viewsc];//添加到View上
   [viewsc release];
    //按钮数组
    NSArray *arr = @[@"手工市集",@"材料市集"];
    self.btnArr = [NSMutableArray array];//按钮可变数组
    self.lineArr = [NSMutableArray array];//线的可变数组
    //遍历按钮
    for (NSInteger i = 0; i < 2; i++) {
        //创建按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        //按钮位置
        btn.frame = CGRectMake(i * self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, 39);
        //按钮名字
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        //按钮开始颜色
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //按钮tag值
        btn.tag = 1000 + i;
        //按钮点击方法
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        //添加
        [self.btnArr addObject:btn];
        [viewsc addSubview:btn];
        //创建线
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 * i, 39, self.view.frame.size.width / 2, 1)];
        //线的颜色
        line.backgroundColor = [UIColor whiteColor];
        //添加到view上
        [viewsc addSubview:line];
        line.tag = 2000 + i;//tag值
        [self.lineArr addObject:line];//添加到可变数组里
        [line release];
        //如果是数组的第一个让按钮颜色和 view颜色变成红色
        if (i == 0) {
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            line.backgroundColor = [UIColor redColor];
        }
        
    }
    
}
#pragma mark - 手工市集 材料市集  按钮点击方法

- (void)btnAction:(UIButton *)btn
{
    //设置scrollView的偏移量
    [self.scrollview setContentOffset:CGPointMake(self.view.frame.size.width * (btn.tag - 1000), -60) animated:YES];
    //按钮开始颜色
    for (UIButton *btn in _btnArr) {
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    //横线开始颜色
    for (UIView *line in _lineArr) {
        line.backgroundColor = [UIColor whiteColor];
    }
    //点击之后变色
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    UIView *line = [self.view viewWithTag:btn.tag + 1000];
    line.backgroundColor = [UIColor redColor];
}
#pragma mark - tableview的header
- (void)createView
{
    //创建一个View
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 180)];
    headerView.backgroundColor = [UIColor whiteColor];
    [self.tableview addSubview:headerView];//view放在tableview上
    self.tableview.tableHeaderView = headerView;//view作为tableview的头部
    [headerView release];

    //header上的View View里装得CollectionView 按钮
    HeaderView *h = [[HeaderView alloc]initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 100)];
    h.backgroundColor = [UIColor yellowColor];
    [headerView addSubview:h];
    [h release];


}
#pragma mark - tableview必须实现的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

        return _dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        
        ShopTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        ShopModel *s =_dataArr[indexPath.row];
        [cell.bgimg sd_setImageWithURL:[NSURL URLWithString:s.host_pic]];//图片
        cell.titlelabel.text = s.topic_name;//标题
//        NSLog(@"%@",_DataArr);
        return cell;

    
}
#pragma mark - tableview的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
#pragma mark - tableview获取数据
- (void)data
{
    NSString *str = @"http://m.shougongke.com/index.php?c=Shiji&a=product&vid=15";
    [AFNnetWork GETwithURL:str completion:^(id result) {
        NSArray *arr = result[@"data"][@"topic"];
        self.dataArr = [ShopModel modelHandlerWithArray:arr];
        
        [_tableview reloadData];//刷新
    }];

    [self.tableview.mj_header endRefreshing];
}
#pragma mark - Tableview刷新加载
- (void)TableviewRefresh
{
    //头部刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 0;
        [self data];//数据
    }];
    //显示的名字
    [header setTitle:@"我刷我刷我刷刷刷" forState:MJRefreshStatePulling];
    [header beginRefreshing];//开始刷新
    self.tableview.mj_header = header;
    //加载
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _page +=10;
        [self table];
    }];
    self.tableview.mj_footer = footer;
}
- (void)table
{
    NSString * str = [[@"http://m.shougongke.com/index.php?c=Shiji&a=topicList&" stringByAppendingString:[NSString stringWithFormat:@"last_id=%ld",_page]]stringByAppendingString:@"&page=product&vid=15"];
    [AFNnetWork GETwithURL:str completion:^(id result) {
        NSArray *arr = result[@"data"];
        NSArray *atemp = [ShopModel modelHandlerWithArray:arr];
        for (ShopModel *f in atemp) {
            [self.dataArr addObject:f];//都放在可变数组里
        }
        [self.tableview reloadData];
    }];
    [self.tableview.mj_footer endRefreshing];

}
#pragma mark - collectionView 数据
- (void)datacol
{
    NSString *str = @"http://m.shougongke.com/index.php?c=Shiji&vid=15";
  [AFNnetWork GETwithURL:str completion:^(id result) {
      NSArray *arr = result[@"data"][@"topic"];
      self.mDataArr = [ShopModel modelHandlerWithArray:arr];
      [self.materialView.mj_header endRefreshing];
      [_materialView reloadData];
      //        NSLog(@"%@",arr);
      
      [self creat];
   
  }];
}

//#pragma mark - CollectionView的刷新加载
//- (void)CollectionRefresh
//{
//    MJRefreshNormalHeader *colheader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        _page = 0;
//        [self datacol];
//    }];
//    [colheader setTitle:@"我刷我刷我刷刷刷" forState:MJRefreshStatePulling];
//    [colheader beginRefreshing];
//    self.materialView.mj_header = colheader;
//    MJRefreshAutoFooter *colfooter = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
//        _page +=10;
//        
//        [self creat];
//    }];
//    self.tableview.mj_footer = colfooter;
//    
//}
- (void)coll
{
    NSString * str = [[@"http://m.shougongke.com/index.php?c=Shiji&a=topicList&" stringByAppendingString:[NSString stringWithFormat:@"last_id=%ld",_page]]stringByAppendingString:@"&page=product&vid=15"];
    [AFNnetWork GETwithURL:str completion:^(id result) {
        NSArray *arr = result[@"data"];
        NSArray *atemp = [ShopModel modelHandlerWithArray:arr];
        for (ShopModel *f in atemp) {
            [self.mDataArr addObject:f];
        }
        [self.materialView reloadData];
    }];
    [self.materialView.mj_footer endRefreshing];
}
#pragma mark - scrollView的拖拽方法
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(scrollView == _scrollview){
        
        NSInteger i= scrollView.contentOffset.x / self.view.frame.size.width;
        for (UIButton *btn in _btnArr) {
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        [_btnArr[i] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        for (UIView *line in _lineArr) {
            line.backgroundColor = [UIColor whiteColor];
        }
        [_lineArr[i] setBackgroundColor:[UIColor redColor]];
    }

}
#pragma mark - collectionView必须实现的两个方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _mDataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
    
        
    
    MaterialCollectionViewCell *mcell = [collectionView dequeueReusableCellWithReuseIdentifier:@"matercell" forIndexPath:indexPath];
    ShopModel *s =_mDataArr[indexPath.item];
    [mcell.bgimg sd_setImageWithURL:[NSURL URLWithString:s.host_pic]];//图片
    mcell.titlelabel.text = s.topic_name;//名字
        return mcell;
  
        
}
#pragma mark - tableview点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopModel *s = _dataArr[indexPath.row];
    //templateid 等于2和等于1跳转的页面不一样
    if ([s.templateid  isEqual: @"2"]) {
        
        SecondTableviewContentViewController *seccontent = [[SecondTableviewContentViewController alloc]init];
        seccontent.strid = s.topic_id;
        [self.navigationController pushViewController:seccontent animated:YES];
    }
    else if ([s.templateid  isEqual: @"1"])
    {
        SecondTwoViewController *sec = [[SecondTwoViewController alloc]init];
        sec.strid = s.topic_id;
        [self.navigationController pushViewController:sec animated:YES];
        
    }
}
#pragma mark - CollectionView点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShopModel *s = _mDataArr[indexPath.item];
    //如果参数templateid 为2 条转
    if ([s.templateid  isEqual: @"2"]) {
        
        SecondTableviewContentViewController *seccontent = [[SecondTableviewContentViewController alloc]init];
        seccontent.strid = s.topic_id;
        [self.navigationController pushViewController:seccontent animated:YES];
    }
    else if ([s.templateid  isEqual: @"1"])
    {
        SecondTwoViewController *sec = [[SecondTwoViewController alloc]init];
        sec.strid = s.topic_id;
        [self.navigationController pushViewController:sec animated:YES];
    }
}
- (void)s
{
    SearchViewController *se = [[SearchViewController alloc]init];
    UINavigationController *uina = [[UINavigationController alloc]initWithRootViewController:se];
    [self presentViewController:uina animated:YES completion:^{
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
